#!/usr/bin/env bash

help(){
    cat<<__EOF__
Usage:  m dns [OPTIONS]

Description:  Manage DNS settings on macOS

Options:
  --help                Show this help message
  --list                List current DNS servers
  --flush               Flush local DNS cache
  --add IP|HOSTNAME     Add a DNS server by IP or hostname
__EOF__
}


flushdns(){
    VERSION=$(sw_vers -productVersion)
    echo "Flushing dns..."
    if echo $VERSION | grep -E '^10\.10(\.[0-3])?$' &>/dev/null; then
        sudo discoveryutil mdnsflushcache
    elif echo $VERSION | grep -E '^10\.6(\.[0-8])?$' &>/dev/null; then
        sudo dscacheutil -flushcache
    else
        sudo killall -HUP mDNSResponder
    fi
}

listdns(){
    echo "List of the DNS servers:"
    cat /etc/resolv.conf | grep nameserver | cut -b 11-
}

adddns(){
    [ -z "${1}" ] && help && exit 1
    sudo sh -c "echo nameserver '${1}' >> /etc/resolv.conf"
    echo "${1} added"
}


case $1 in
    --help)
        help
        ;;
    --list)
        listdns
        ;;
    --add)
        shift
        adddns "$@"
        ;;
    --flush)
        flushdns
        ;;
    *)
        help && exit 1
        ;;
esac
